<template>
  <div class="coverage-container">
    <!-- 页面标题 -->
    <!-- <div class="page-header">
        <h2>险种管理</h2>
        <p>管理农业保险险种信息，包括险种编码、名称、类型等详细信息</p>
    </div> -->

    <!-- 搜索和操作区域 -->
    <div class="search-section">
      <el-card shadow="never" class="search-card">
        <el-form :model="searchForm" :inline="true" class="search-form">
          <el-form-item label="险种编码">
            <el-input v-model="searchForm.coverageCode" placeholder="请输入险种编码" clearable
                      style="width: 200px" />
          </el-form-item>
          <el-form-item label="险种名称">
            <el-input v-model="searchForm.coverageName" placeholder="请输入险种名称" clearable
                      style="width: 200px" />
          </el-form-item>
          <el-form-item label="险种类型">
            <el-select v-model="searchForm.coverageType" placeholder="请选择险种类型" clearable
                       style="width: 150px">
              <el-option label="种植业" :value="1" />
              <el-option label="养殖业" :value="2" />
              <el-option label="其他农险" :value="3" />
            </el-select>
          </el-form-item>
          <el-form-item label="险种状态">
            <el-select v-model="searchForm.coverageStatus" placeholder="请选择状态" clearable
                       style="width: 120px">
              <el-option label="启用" :value="1" />
              <el-option label="停用" :value="2" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch" :icon="Search">
              查询
            </el-button>
            <el-button @click="handleReset" :icon="Refresh">
              重置
            </el-button>
            <el-button type="success" @click="handleAdd" :icon="Plus">
              新增险种
            </el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>

    <!-- 数据表格 -->
    <div class="table-section">
      <el-card shadow="never" class="table-card">
        <el-table :data="tableData" v-loading="loading" stripe border style="width: 100%"
                  :header-cell-style="{ background: '#f5f7fa', color: '#606266' }">
          <el-table-column prop="coverageCode" label="险种编码" width="120" />
          <el-table-column prop="coverageName" label="险种名称" width="200" show-overflow-tooltip />
          <el-table-column prop="coverageType" label="险种类型" width="100">
            <template #default="{ row }">
              <el-tag :type="getCoverageTypeTag(row.coverageType)">
                {{ getCoverageTypeText(row.coverageType) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="insurableSubject" label="可保项目" width="200" show-overflow-tooltip />
          <el-table-column prop="unitInsuredAmount" label="单位保额" width="120">
            <template #default="{ row }">
              <el-tooltip :content="getInsuredUnit(row.coverageType)" placement="top"
                          :disabled="!getInsuredUnit(row.coverageType)">
                <span class="insured-amount">{{ formatMoney(row.unitInsuredAmount) }}</span>
              </el-tooltip>
            </template>
          </el-table-column>
          <el-table-column prop="termMin" label="最短期限(天)" width="120" />
          <el-table-column prop="termMax" label="最长期限(天)" width="120" />
          <el-table-column prop="coverageStatus" label="状态" width="80">
            <template #default="{ row }">
              <el-tag :type="row.coverageStatus === 1 ? 'success' : 'danger'">
                {{ row.coverageStatus === 1 ? '启用' : '停用' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="createTime" label="创建时间" width="200">
            <template #default="{ row }">
              {{ formatDateTime(row.createTime) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="350" fixed="right">
            <template #default="{ row }">
              <el-button type="primary" size="small" @click="handleView(row)" :icon="View">
                查看
              </el-button>
              <el-button type="warning" size="small" @click="handleEdit(row)" :icon="Edit">
                编辑
              </el-button>
              <el-button :type="row.coverageStatus === 1 ? 'danger' : 'success'" size="small"
                         @click="handleToggleStatus(row)" :icon="row.coverageStatus === 1 ? 'Lock' : 'Unlock'">
                {{ row.coverageStatus === 1 ? '停用' : '启用' }}
              </el-button>
              <el-button type="danger" size="small" @click="handleDelete(row)" :icon="Delete">
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="pagination-container">
          <el-pagination v-model:current-page="pagination.currentPage" v-model:page-size="pagination.pageSize"
                         :page-sizes="[5, 10, 20, 50, 100]" :total="pagination.total"
                         layout="total, sizes, prev, pager, next, jumper" @size-change="handleSizeChange"
                         @current-change="handleCurrentChange" />
        </div>
      </el-card>
    </div>

    <!-- 新增/编辑对话框 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="800px" :close-on-click-modal="false"
               :close-on-press-escape="false"><br>
      <el-form ref="formRef" :model="formData" :rules="formRules" label-width="120px" class="form-container">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="险种编码" prop="coverageCode">
              <el-input v-model="formData.coverageCode" placeholder="请输入险种编码" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="险种名称" prop="coverageName">
              <el-input v-model="formData.coverageName" placeholder="请输入险种名称" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="险种类型" prop="coverageType">
              <el-select v-model="formData.coverageType" placeholder="请选择险种类型" style="width: 100%">
                <el-option label="种植业" :value="1" />
                <el-option label="养殖业" :value="2" />
                <el-option label="其他农险" :value="3" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="险种状态" prop="coverageStatus">
              <el-select v-model="formData.coverageStatus" placeholder="请选择状态" style="width: 100%">
                <el-option label="启用" :value="1" />
                <el-option label="停用" :value="2" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="可保项目" prop="insurableSubject">
          <el-input v-model="formData.insurableSubject" type="textarea" :rows="2" placeholder="请输入可保项目描述" />
        </el-form-item>

        <el-form-item label="保险责任范围" prop="insuranceScope">
          <el-input v-model="formData.insuranceScope" type="textarea" :rows="3" placeholder="请输入保险责任范围" />
        </el-form-item>

        <el-form-item label="责任免除条款" prop="exclusionClause">
          <el-input v-model="formData.exclusionClause" type="textarea" :rows="3" placeholder="请输入责任免除条款" />
        </el-form-item>

        <el-form-item label="单位保额" prop="unitInsuredAmount">
          <el-input-number v-model="formData.unitInsuredAmount" :min="0" :precision="2" placeholder="请输入单位保额"
                           style="width: 100%" />
        </el-form-item>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="最短保险期限" prop="termMin">
              <el-input-number v-model="formData.termMin" :min="1" placeholder="请输入最短保险期限(天)"
                               style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="最长保险期限" prop="termMax">
              <el-input-number v-model="formData.termMax" :min="1" placeholder="请输入最长保险期限(天)"
                               style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="投保所需材料" prop="requiredMaterials">
          <el-input v-model="formData.requiredMaterials" type="textarea" :rows="2" placeholder="请输入投保所需材料" />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleCancel">取消</el-button>
          <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
            {{ isEdit ? '更新' : '保存' }}
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 查看详情对话框 -->
    <el-dialog v-model="viewDialogVisible" title="险种详情" width="800px" :close-on-click-modal="false">
      <div class="detail-container" v-if="viewData">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="险种编码">{{ viewData.coverageCode }}</el-descriptions-item>
          <el-descriptions-item label="险种名称">{{ viewData.coverageName }}</el-descriptions-item>
          <el-descriptions-item label="险种类型">
            <el-tag :type="getCoverageTypeTag(viewData.coverageType)">
              {{ getCoverageTypeText(viewData.coverageType) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="险种状态">
            <el-tag :type="viewData.coverageStatus === 1 ? 'success' : 'danger'">
              {{ viewData.coverageStatus === 1 ? '启用' : '停用' }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="可保项目" :span="2">{{ viewData.insurableSubject }}</el-descriptions-item>
          <el-descriptions-item label="保险责任范围" :span="2">{{ viewData.insuranceScope }}</el-descriptions-item>
          <el-descriptions-item label="责任免除条款" :span="2">{{ viewData.exclusionClause }}</el-descriptions-item>
          <el-descriptions-item label="单位保额">
            <el-tooltip :content="getInsuredUnit(viewData.coverageType)" placement="top"
                        :disabled="!getInsuredUnit(viewData.coverageType)">
              <span class="insured-amount">{{ formatMoney(viewData.unitInsuredAmount) }}</span>
            </el-tooltip>
          </el-descriptions-item>
          <el-descriptions-item label="最短保险期限">{{ viewData.termMin }}天</el-descriptions-item>
          <el-descriptions-item label="最长保险期限">{{ viewData.termMax }}天</el-descriptions-item>
          <el-descriptions-item label="投保所需材料" :span="2">{{ viewData.requiredMaterials
            }}</el-descriptions-item>
          <el-descriptions-item label="创建时间">{{ formatDateTime(viewData.createTime) }}</el-descriptions-item>
          <!-- <el-descriptions-item label="更新时间">{{ formatDateTime(viewData.updateTime) }}</el-descriptions-item> -->
        </el-descriptions>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Refresh, Plus, View, Edit, Delete, Lock, Unlock } from '@element-plus/icons-vue'
import hxxp from '@/utils/hxxp'

// 响应式数据
const loading = ref(false)
const submitLoading = ref(false)
const dialogVisible = ref(false)
const viewDialogVisible = ref(false)
const isEdit = ref(false)
const dialogTitle = ref('')

// 搜索表单
const searchForm = reactive({
  coverageCode: '',
  coverageName: '',
  coverageType: null,
  coverageStatus: null
})

// 分页数据
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 表格数据
const tableData = ref([])

// 表单数据
const formData = reactive({
  coverageId: '',
  coverageCode: '',
  coverageName: '',
  coverageType: null,
  insurableSubject: '',
  insuranceScope: '',
  exclusionClause: '',
  unitInsuredAmount: null,
  termMin: null,
  termMax: null,
  requiredMaterials: '',
  coverageStatus: 1
})

// 查看数据
const viewData = ref(null)

// 表单引用
const formRef = ref()

// 表单验证规则
const formRules = {
  coverageCode: [
    { required: true, message: '请输入险种编码', trigger: 'blur' },
    { min: 2, max: 32, message: '长度在 2 到 32 个字符', trigger: 'blur' }
  ],
  coverageName: [
    { required: true, message: '请输入险种名称', trigger: 'blur' },
    { min: 2, max: 64, message: '长度在 2 到 64 个字符', trigger: 'blur' }
  ],
  coverageType: [
    { required: true, message: '请选择险种类型', trigger: 'change' }
  ],
  insurableSubject: [
    { required: true, message: '请输入可保项目', trigger: 'blur' }
  ],
  insuranceScope: [
    { required: true, message: '请输入保险责任范围', trigger: 'blur' }
  ],
  exclusionClause: [
    { required: true, message: '请输入责任免除条款', trigger: 'blur' }
  ],
  unitInsuredAmount: [
    { required: true, message: '请输入单位保额', trigger: 'blur' }
  ],
  termMin: [
    { required: true, message: '请输入最短保险期限', trigger: 'blur' }
  ],
  termMax: [
    { required: true, message: '请输入最长保险期限', trigger: 'blur' }
  ],
  requiredMaterials: [
    { required: true, message: '请输入投保所需材料', trigger: 'blur' }
  ],
  coverageStatus: [
    { required: true, message: '请选择险种状态', trigger: 'change' }
  ]
}

// 工具函数
const getCoverageTypeText = (type) => {
  const typeMap = {
    1: '种植业',
    2: '养殖业',
    3: '其他农险'
  }
  return typeMap[type] || '未知'
}

const getCoverageTypeTag = (type) => {
  const tagMap = {
    1: 'success',
    2: 'warning',
    3: 'info'
  }
  return tagMap[type] || 'info'
}

const formatMoney = (amount) => {
  if (!amount) return '0.00'
  return `¥${Number(amount).toFixed(2)}`
}

const formatDateTime = (dateTime) => {
  if (!dateTime) return '-'
  return new Date(dateTime).toLocaleString('zh-CN')
}

// 获取保额单位
const getInsuredUnit = (coverageType) => {
  if (coverageType === 1) {
    return '元/亩'
  } else if (coverageType === 2) {
    return '元/头或元/只'
  }
  return ''
}


// 重置表单
const resetForm = () => {
  Object.assign(formData, {
    coverageId: '',
    coverageCode: '',
    coverageName: '',
    coverageType: null,
    insurableSubject: '',
    insuranceScope: '',
    exclusionClause: '',
    unitInsuredAmount: null,
    termMin: null,
    termMax: null,
    requiredMaterials: '',
    coverageStatus: 1
  })
  if (formRef.value) {
    formRef.value.clearValidate()
  }
}

// 获取险种列表
const getCoverageList = async () => {
  try {
    loading.value = true
    const params = {
      pageNum: pagination.currentPage,
      pageSize: pagination.pageSize,
      ...searchForm
    }

    // 移除空值参数
    Object.keys(params).forEach(key => {
      if (params[key] === '' || params[key] === null || params[key] === undefined) {
        delete params[key]
      }
    })

    const response = await hxxp.get('/coverage/list', { params })
    console.log(response);

    if (response.code === 100200) {

      tableData.value = response.data.list || []
      pagination.total = response.data.total || 0
      pagination.currentPage = response.data.pageNum || 1
      pagination.pageSize = response.data.pageSize || 5
    } else {
      ElMessage.error(response.message || '获取险种列表失败')
    }
  } catch (error) {
    console.error('获取险种列表失败:', error)
    ElMessage.error('获取险种列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.currentPage = 1
  getCoverageList()
}

// 重置搜索
const handleReset = () => {
  Object.assign(searchForm, {
    coverageCode: '',
    coverageName: '',
    coverageType: null,
    coverageStatus: null
  })
  pagination.currentPage = 1
  getCoverageList()
}

// 新增
const handleAdd = () => {
  resetForm()
  isEdit.value = false
  dialogTitle.value = '新增险种'
  dialogVisible.value = true
}

// 编辑
const handleEdit = (row) => {
  resetForm()
  Object.assign(formData, { ...row })
  isEdit.value = true
  dialogTitle.value = '编辑险种'
  dialogVisible.value = true
}

// 查看详情
const handleView = (row) => {
  viewData.value = { ...row }
  viewDialogVisible.value = true
}

// 删除
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(
        `确定要删除险种"${row.coverageName}"吗？`,
        '删除确认',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
    )

    const response = await hxxp.delete(`/coverage/${row.coverageId}`)

    if (response.code === 100200) {
      ElMessage.success('删除成功')
      getCoverageList()
    } else {
      ElMessage.error(response.message || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

// 切换状态
const handleToggleStatus = async (row) => {
  const action = row.coverageStatus === 1 ? '停用' : '启用'

  try {
    await ElMessageBox.confirm(
        `确定要${action}险种"${row.coverageName}"吗？`,
        `${action}确认`,
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
    )

    const newStatus = row.coverageStatus === 1 ? 2 : 1
    const response = await hxxp.put(`/coverage/${row.coverageId}/${newStatus}`)

    if (response.code === 100200) {
      ElMessage.success(`${action}成功`)
      getCoverageList()
    } else {
      ElMessage.error(response.msg || `${action}失败`)
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error(`${action}失败:`, error)
      ElMessage.error(`${action}失败`)
    }
  }
}

// 提交表单
const handleSubmit = async () => {
  try {
    await formRef.value.validate()
    submitLoading.value = true

    const url = isEdit.value ? `/coverage/${formData.coverageId}` : '/coverage'
    const method = isEdit.value ? 'put' : 'post'

    const response = await hxxp[method](url, formData)

    if (response.code === 100200) {
      ElMessage.success(isEdit.value ? '更新成功' : '新增成功')
      dialogVisible.value = false
      getCoverageList()
    } else {
      ElMessage.error(response.message || (isEdit.value ? '更新失败' : '新增失败'))
    }
  } catch (error) {
    console.error('提交失败:', error)
    ElMessage.error(isEdit.value ? '更新失败' : '新增失败')
  } finally {
    submitLoading.value = false
  }
}

// 取消
const handleCancel = () => {
  dialogVisible.value = false
  resetForm()
}

// 分页大小改变
const handleSizeChange = (val) => {
  pagination.pageSize = val
  pagination.currentPage = 1
  getCoverageList()
}

// 当前页改变
const handleCurrentChange = (val) => {
  pagination.currentPage = val
  getCoverageList()
}

// 页面加载时获取数据
onMounted(() => {
  getCoverageList()
})
</script>

<style scoped>
.coverage-container {
  padding: 0;
}

.page-header {
  margin-bottom: 20px;
  padding: 20px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 8px;
  color: white;
}

.page-header h2 {
  margin: 0 0 8px 0;
  font-size: 24px;
  font-weight: 600;
}

.page-header p {
  margin: 0;
  opacity: 0.9;
  font-size: 14px;
}

.search-section {
  margin-bottom: 20px;
}

.search-card {
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.search-form {
  margin: 0;
}

.table-section {
  margin-bottom: 20px;
}

.table-card {
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.form-container {
  max-height: 60vh;
  overflow-y: auto;
}

.detail-container {
  padding: 20px 0;
}

.dialog-footer {
  text-align: right;
}

/* 表格样式优化 */
:deep(.el-table) {
  border-radius: 8px;
  overflow: hidden;
}

:deep(.el-table th) {
  background: #f8f9fa !important;
  color: #495057 !important;
  font-weight: 600;
}

:deep(.el-table--striped .el-table__body tr.el-table__row--striped td) {
  background: #f8f9fa;
}

:deep(.el-table__row:hover > td) {
  background-color: #e3f2fd !important;
}

/* 按钮样式优化 */
:deep(.el-button) {
  border-radius: 6px;
  font-weight: 500;
}

:deep(.el-button--small) {
  padding: 5px 12px;
  font-size: 12px;
}

/* 表单样式优化 */
:deep(.el-form-item__label) {
  font-weight: 500;
  color: #606266;
}

:deep(.el-input__inner) {
  border-radius: 6px;
}

:deep(.el-textarea__inner) {
  border-radius: 6px;
}

/* 对话框样式优化 */
:deep(.el-dialog) {
  border-radius: 12px;
}

:deep(.el-dialog__header) {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border-radius: 12px 12px 0 0;
  padding: 20px 24px;
}

:deep(.el-dialog__title) {
  color: white;
  font-weight: 600;
}

:deep(.el-dialog__headerbtn .el-dialog__close) {
  color: white;
}

/* 标签样式 */
:deep(.el-tag) {
  border-radius: 4px;
  font-weight: 500;
}

/* 描述列表样式 */
:deep(.el-descriptions) {
  border-radius: 8px;
}

:deep(.el-descriptions__label) {
  font-weight: 600;
  color: #606266;
}

/* 保额悬停样式 */
.insured-amount {
  cursor: help;
  transition: color 0.3s ease;
}

.insured-amount:hover {
  color: #409eff;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .search-form {
    flex-direction: column;
  }

  .search-form .el-form-item {
    margin-right: 0;
    margin-bottom: 16px;
  }

  .page-header {
    padding: 16px;
  }

  .page-header h2 {
    font-size: 20px;
  }
}
</style>
